package excel

import (
	"errors"
	"reflect"
	"strings"

	"github.com/huandu/xstrings"
)

const defaultTag = "excel"

//
func getStructFields(v interface{}) ([]string, []string, error) {
	rv := reflect.ValueOf(v)
	if !rv.IsValid() || rv.Kind() != reflect.Ptr || rv.IsNil() {
		return nil, nil, errors.New("unsuport type")
	}
	rt := reflect.TypeOf(v)
	rte := rt.Elem()
	switch rte.Kind() {
	case reflect.Struct:
		return wrapStructFields2Slice(rte)
	default:
		return nil, nil, errors.New("only support struct")
	}
}

func wrapStructFields2Slice(t reflect.Type) (fs, ths []string, err error) {
	for i := 0; i < t.NumField(); i++ {
		f, t := getMapKey(t.Field(i))
		if len(f) > 0 && len(t) > 0 {
			fs = append(fs, f)
			ths = append(ths, t)
		}
	}
	if len(fs) == 0 || len(ths) == 0 {
		err = errors.New("no field matched")
	}
	return fs, ths, err
}

func getMapKey(sf reflect.StructField) (field, tableHeader string) {
	key := sf.Tag.Get(defaultTag)
	if len(key) == 0 {
		s := xstrings.ToSnakeCase(sf.Name)
		field, tableHeader = s, s
		return
	}
	if key != "" && key != "-" {
		options := strings.Split(key, "~")
		if len(options) > 1 {
			field = options[0]
			tableHeader = options[1]
			return
		}
		field = options[0]
		tableHeader = options[0]
		return
	}
	return
}
